<template>
  <div class="chat-container">
    <!-- 顶部聊天对象信息栏 -->
    <div class="chat-header">
      <div class="header-left">
        <el-button
            circle
            :icon="ArrowLeft"
            @click="router.back()"
            class="back-btn"
        />
        <div class="user-info">
          <el-avatar
              class="user-avatar"
              :size="44"
              :src="getAvatarUrl(targetUser.avatar)"
              alt="用户头像"
          />
          <div class="user-details">
            <div class="nickname">{{ targetUser.nickName }}</div>
            <div class="connection-status">
          <span class="online-status" :class="{ online: isOnline }">
            {{ isOnline ? '在线' : '离线' }}
          </span>
              <span class="ws-status" :class="{ connected: isConnected }">
            {{ isConnected ? '● 已连接' : '● 连接中...' }}
          </span>
            </div>
          </div>
        </div>
      </div>
      <div class="header-actions">
        <el-button
            circle
            :icon="MoreFilled"
            @click="showMoreActions"
        />
      </div>
    </div>

    <!-- 消息区域 -->
    <div class="messages-container" ref="messagesContainer">
      <!-- 加载更多消息 -->
      <div class="load-more" v-if="hasMoreMessages" @click="loadMoreMessages">
        <el-button text type="primary" :loading="loadingMore">
          {{ loadingMore ? '加载中...' : '加载更多历史消息' }}
        </el-button>
      </div>

      <!-- 消息列表 -->
      <div
          class="message-item"
          v-for="message in messages"
          :key="message.id"
          :class="{
          'own-message': message.senderId === currentUserId,
          'other-message': message.senderId !== currentUserId
        }"
      >
        <!-- 对方消息显示头像 -->
        <el-avatar
            v-if="message.senderId !== currentUserId"
            class="message-avatar"
            :size="40"
            :src="getAvatarUrl(targetUser.avatar)"
        />

        <div class="message-content">
          <!-- 消息文本 -->
          <div class="message-bubble" v-if="message.messageType === 'TEXT'">
            {{ message.content }}
          </div>

          <!-- 消息时间 -->
          <div class="message-time">
            {{ formatDateTime(message.sendTime) }}
          </div>
        </div>

        <!-- 自己消息显示头像 -->
        <el-avatar
            v-if="message.senderId === currentUserId"
            class="message-avatar"
            :size="40"
            :src="getCurrentUserAvatar()"
        />
      </div>

      <!-- 输入消息时的加载状态 -->
      <div class="sending-indicator" v-if="sending">
        <el-icon class="is-loading"><Loading /></el-icon>
        发送中...
      </div>
      <!-- 正在输入提示 -->
      <div class="typing-indicator" v-if="typingStatus">
        {{ typingStatus }}
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <div class="input-toolbar">
        <el-button
            circle
            :icon="Picture"
            @click="handleImageSelect"
            title="发送图片"
        />
        <el-button
            circle
            :icon="Microphone"
            @click="startVoiceRecording"
            title="语音输入"
        />
        <el-button
            circle
            :icon="Files"
            @click="handleFileSelect"
            title="发送文件"
        />
      </div>
      <div class="input-area">
        <el-input
            @input="handleInput"
            v-model="inputMessage"
            type="textarea"
            :rows="2"
            :maxlength="500"
            placeholder="输入消息..."
            @keydown.enter.exact.prevent="handleSendMessage"
            resize="none"
            class="message-input"
        />
        <div class="input-actions">
          <span class="char-count">{{ inputMessage.length }}/500</span>
          <el-button
              type="primary"
              :icon="Promotion"
              @click="handleSendMessage"
              :disabled="!inputMessage.trim()"
              :loading="sending"
              class="send-btn"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {userStore} from "../store/UserStore.js";
import { formatDateTime } from '../utils/date-utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  MoreFilled,
  Picture,
  Microphone,
  Promotion,
  Loading,
  ArrowLeft,
  Files
} from '@element-plus/icons-vue'
import axios from '../api/index.js'

// 路由和状态管理
const route = useRoute()
const router = useRouter()
const store=userStore();
// 响应式数据
const targetUser = reactive({
  userId: '',
  nickName: '',
  avatar: ''
})

const currentUserId = ref(store.cur_user.id) // 实际项目中应从登录状态获取
const messages = ref([])
const inputMessage = ref('')
const sending = ref(false)
const loadingMore = ref(false)
const hasMoreMessages = ref(true)
const isOnline = ref(true)
const messagesContainer = ref(null)
// 新增WebSocket相关变量
const ws = ref(null)
const isConnected = ref(false)
const typingStatus = ref('') // 正在输入提示
// 添加定时器变量
let typingTimer = null
// 建立WebSocket连接
const connectWebSocket = () => {
  const token = store.jwt
  if (!token) {
    ElMessage.error('未登录，无法连接聊天')
    return
  }

  // 正确的 WebSocket URL 格式
  const wsUrl = `ws://localhost:8080/ws/chat?token=${encodeURIComponent(token)}`
  console.log('WebSocket URL:', wsUrl)
  // 关闭现有连接
  if (ws.value) {
    ws.value.close()
  }

  ws.value = new WebSocket(wsUrl)

  ws.value.onopen = () => {
    console.log('WebSocket连接成功')
    isConnected.value = true
    // 连接成功后加载消息并标记已读
    loadMessages()
    sendReadReceipt()
  }

  ws.value.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data)
      handleWebSocketMessage(message)
    } catch (error) {
      console.error('解析WebSocket消息失败:', error)
    }
  }

  ws.value.onclose = (event) => {
    console.log('WebSocket连接关闭，代码:', event.code, '原因:', event.reason)
    isConnected.value = false

    // 非正常关闭时重连
    if (event.code !== 1000) {
      console.log('3秒后尝试重连...')
      setTimeout(connectWebSocket, 3000)
    }
  }

  ws.value.onerror = (error) => {
    console.error('WebSocket错误:', error)
    isConnected.value = false
    ElMessage.error('连接服务器失败')
  }
}
// 处理接收到的WebSocket消息
const handleWebSocketMessage = (message) => {
  console.log('收到WebSocket消息:', message)

  switch (message.type) {
    case 'MESSAGE':
      // 收到新消息
      if (message.message) {
        // 检查是否是自己发送的消息的确认
        const tempIndex = messages.value.findIndex(
            msg => msg.id.toString().startsWith('temp-') &&
                msg.senderId === message.message.senderId &&
                msg.content === message.message.content
        )

        if (tempIndex > -1) {
          // 替换临时消息为正式消息
          messages.value.splice(tempIndex, 1, message.message)
        } else if (message.message.receiverId === currentUserId.value) {
          // 接收新消息
          messages.value.push(message.message)
          sendReadReceipt()
        }
        scrollToBottom()
      }
      break

    case 'ONLINE_STATUS':
      // 更新在线状态
      if (message.senderId === parseInt(targetUser.userId)) {
        isOnline.value = message.isOnline
        ElMessage.info(`${targetUser.nickName} ${message.isOnline ? '上线了' : '离线了'}`)
      }
      break

    case 'TYPING':
      // 处理输入状态
      if (message.senderId === parseInt(targetUser.userId)) {
        typingStatus.value = '正在输入...'
        // 3秒后清除提示
        clearTimeout(typingTimer)
        typingTimer = setTimeout(() => {
          typingStatus.value = ''
        }, 3000)
      }
      break

    case 'READ':
      // 处理已读回执
      if (message.senderId === parseInt(targetUser.userId)) {
        updateMessagesAsRead(targetUser.userId)
      }
      break

    case 'ERROR':
      ElMessage.error(message.error || '操作失败')
      break

    default:
      console.warn('未知消息类型:', message.type)
  }
}
// 初始化聊天数据
const initializeChat = async () => {
  // 从路由参数获取目标用户信息
  targetUser.userId = route.query.targetUserId || ''
  targetUser.nickName = route.query.targetUserName || '未知用户'
  targetUser.avatar = route.query.targetUserAvatar || ''

  if (!targetUser.userId) {
    ElMessage.error('无效的聊天对象')
    router.back()
    return
  }

  // 先建立WebSocket连接，连接成功后会自动加载消息
  connectWebSocket()
}
// 加载消息
const loadMessages = async (loadMore = false) => {
  if (loadMore) {
    loadingMore.value = true
  }

  try {
    // 计算before参数
    let beforeTime = null
    if (loadMore && messages.value.length > 0) {
      beforeTime = formatDateTime(new Date(messages.value[0].sendTime))
    }

    const response = await axios.get(`/chat/history`, {
      params: {
        userId: currentUserId.value,
        targetUserId: targetUser.userId,
        before: beforeTime,
        limit: 20
      }
    })
    console.log('加载消息:', response)
    if (response && response.list) {
      if (loadMore) {
        // 添加到列表头部
        messages.value.unshift(...response.list)
      } else {
        console.log('加载消息3:', response)
        messages.value = response.list
        scrollToBottom()
      }
      console.log('加载消息2:', response)
      hasMoreMessages.value = response.pages > response.current
    }
  } catch (error) {
    console.error('加载消息失败:', error)
    ElMessage.error('加载消息失败')
  } finally {
    loadingMore.value = false
  }
}
// 加载更多历史消息
const loadMoreMessages = () => {
  loadMessages(true)
}
// 监听输入框变化，发送正在输入状态,typingMessage
const handleInput = () => {
  if (!isConnected.value) return

  const typingMessage = {
    type: 'TYPING',
    senderId: currentUserId.value,
    receiverId: targetUser.userId,
    isTyping: inputMessage.value.trim().length > 0,
    timestamp: formatDateTime(new Date())
  }
  ws.value.send(JSON.stringify(typingMessage))
}
// 发送消息
const handleSendMessage = async () => {
  if (!inputMessage.value.trim() || !isConnected.value) return

  const messageContent = inputMessage.value.trim()
  inputMessage.value = ''
  sending.value = true

  try {
    // 构造符合后端格式的消息
    const wsMessage = {
      type: 'MESSAGE',
      message: {
        senderId: currentUserId.value,
        receiverId: parseInt(targetUser.userId),
        content: messageContent,
        messageType: 'TEXT'
        // 不需要手动设置 sendTime，后端会自动设置
      },
      timestamp: formatDateTime(new Date())
    }

    // 通过WebSocket发送
    ws.value.send(JSON.stringify(wsMessage))

    // 乐观更新：先添加到消息列表，使用带前缀的临时ID
    const tempId = `temp-${Date.now()}`
    const optimisticMessage = {
      id: tempId,  // 使用带前缀的临时ID
      senderId: currentUserId.value,
      receiverId: parseInt(targetUser.userId),
      content: messageContent,
      messageType: 'TEXT',
      sendTime: formatDateTime(new Date()),
      status: 'SENT'
    }
    messages.value.push(optimisticMessage)
    scrollToBottom()

  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败，请重试')
    // 发送失败时移除临时消息
    const lastMsg = messages.value[messages.value.length - 1]
    if (lastMsg && lastMsg.id.toString().startsWith('temp-')) {
      messages.value.pop()
    }
  } finally {
    sending.value = false
  }
}
// 发送已读回执
const sendReadReceipt = () => {
  if (!isConnected.value) return

  const readMessage = {
    type: 'READ',
    senderId: currentUserId.value,
    receiverId: targetUser.userId,
    timestamp: formatDateTime(new Date())
  }
  ws.value.send(JSON.stringify(readMessage))
}

// 更新消息为已读状态
const updateMessagesAsRead = (senderId) => {
  messages.value.forEach(msg => {
    if (msg.senderId === senderId && msg.status !== 'READ') {
      msg.status = 'READ'
    }
  })
}


// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 获取对方头像URL
const getAvatarUrl = (avatarName) => {
  if (!avatarName) {
    return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  }

  const baseURL = axios.defaults.baseURL || ''
  const cleanBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL
  return `${cleanBaseURL}/img/avatar/${avatarName}`
}

// 获取当前用户头像（实际项目中应从用户状态获取）
const getCurrentUserAvatar = () => {
  const avatarName = store.cur_user.avatar
  if (!avatarName) {
    return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
  }
  const baseURL = axios.defaults.baseURL || ''
  const cleanBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL
  return `${cleanBaseURL}/img/avatar/${avatarName}`
}

// 更多操作
const showMoreActions = () => {
  ElMessageBox.confirm(
      `确定要删除与 ${targetUser.nickName} 的聊天记录吗？`,
      '删除聊天记录',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    messages.value = []
    ElMessage.success('聊天记录已删除')
  }).catch(() => {
    // 取消操作
  })
}

// 处理图片选择
const handleImageSelect = () => {
  ElMessage.info('图片发送功能开发中...')
}

// 开始语音录制
const startVoiceRecording = () => {
  ElMessage.info('语音消息功能开发中...')
}

// 处理文件选择
const handleFileSelect = () => {
  ElMessage.info('文件发送功能开发中...')
}

// 监听路由变化
watch(
    () => route.query,
    () => {
      initializeChat()
      connectWebSocket()
    }
)

// 生命周期
onMounted(() => {
  initializeChat()
})

onUnmounted(() => {
  // 清理工作
  if (ws.value) {
    ws.value.close(1000, '页面关闭')
  }
  if (typingTimer) {
    clearTimeout(typingTimer)
  }
})
</script>

<style scoped>
.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ws-status {
  font-size: 12px;
  color: #f56c6c;
}

.ws-status.connected {
  color: #67c23a;
}

.online-status {
  font-size: 12px;
  color: #909399;
}

.online-status.online {
  color: #67c23a;
}
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  background-color: #f8f9fa;
  position: relative;
}

/* 头部样式 */
.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  background-color: #fff;
  border-bottom: 1px solid #e8e8e8;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  flex-shrink: 0;
  z-index: 10;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-btn {
  margin-right: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.nickname {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.2;
}

.online-status {
  font-size: 12px;
  color: #999;
  line-height: 1.2;
}

.online-status.online {
  color: #52c41a;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 消息容器样式 */
.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 0; /* 确保flex子元素可以收缩 */
}

.load-more {
  text-align: center;
  padding: 10px 0;
}

/* 消息项样式 */
.message-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.own-message {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
  align-self: flex-end;
  margin-bottom: 4px;
}

.message-content {
  max-width: 65%;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.own-message .message-content {
  align-items: flex-end;
}

.other-message .message-content {
  align-items: flex-start;
}

/* 消息气泡样式 */
.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.4;
  word-wrap: break-word;
  max-width: 100%;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.own-message .message-bubble {
  background: linear-gradient(135deg, #1890ff, #096dd9);
  color: white;
  border-bottom-right-radius: 4px;
}

.other-message .message-bubble {
  background-color: white;
  color: #333;
  border: 1px solid #e8e8e8;
  border-bottom-left-radius: 4px;
}

/* 消息时间样式 */
.message-time {
  font-size: 11px;
  color: #999;
  padding: 0 8px;
  margin-top: 2px;
}

/* 发送中指示器 */
.sending-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px;
  color: #999;
  font-size: 14px;
}

/* 输入容器样式 */
.input-container {
  background-color: #fff;
  border-top: 1px solid #e8e8e8;
  padding: 16px 20px;
  flex-shrink: 0;
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.05);
}

.input-toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.input-area {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-input {
  border-radius: 12px;
}

.message-input :deep(.el-textarea__inner) {
  border-radius: 12px;
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.5;
  border: 1px solid #e0e0e0;
  resize: none;
  transition: all 0.3s ease;
}

.message-input :deep(.el-textarea__inner:focus) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.input-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.char-count {
  font-size: 12px;
  color: #999;
}

.send-btn {
  border-radius: 20px;
  padding: 8px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    height: 100vh;
    padding: 0;
  }

  .chat-header {
    padding: 10px 16px;
    position: sticky;
    top: 0;
  }

  .messages-container {
    padding: 12px 16px;
  }

  .message-content {
    max-width: 75%;
  }

  .input-container {
    padding: 12px 16px;
    position: sticky;
    bottom: 0;
  }

  .message-bubble {
    padding: 10px 14px;
    font-size: 15px;
  }

  .send-btn {
    padding: 8px 16px;
  }
}

@media (min-width: 1200px) {
  .message-content {
    max-width: 60%;
  }
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 确保在移动设备上有良好的触摸体验 */
@media (hover: none) and (pointer: coarse) {
  .messages-container {
    -webkit-overflow-scrolling: touch;
  }

  .message-bubble {
    padding: 14px 18px;
  }
}
</style>